import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_time_period.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/train_plan/get_education_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/education_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///培训计划
class TrainProgramController extends GetxController {
  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 搜索条件
  String? searchX;

  /// 培训类型
  String trainingTypeId = '';
  RxString trainingTypeBack = '请选择'.obs;

  /// 培训级别
  String trainingLevelId = '';
  RxString trainingLevelBack = '请选择'.obs;

  /// 培训状态
  String statusId = '';
  RxString statusBack = '请选择'.obs;

  /// 培训途径
  String trainingChannelsId = '';
  RxString trainingChannelsBack = '请选择'.obs;

  /// 开始时间
  String startDate = '';

  /// 结束时间
  String endDate = '';

  /// 培训途径 1线上 2线下
  List<GetDictAllEntity> currencyTrainingChannels = [];

  ///  状态 0：待提交 1：进行中 2：已结束
  static List<GetDictAllEntity> currencyState = [];

  @override
  void onInit() {
    super.onInit();
    //培训状态  1：进行中 2：已结束 //0：待发起 1：待审批 2：审批中 3：通过 4：驳回
    initCurrencyState();
    //培训途径 1线上 2线下
    initCurrencyTrainingChannels();
  }

  ///培训状态 3：默认 1：进行中 2：已结束
  void selectCurrencyDangerLevelType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '培训状态',
      dataList: currencyState,
      checkedList: [dictEntity1 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity1 = value[0];
        statusId = value[0].getId();
        statusBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  ///培训途径 1线上 2线下
  void selectCurrencyTrainingChannels() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '培训途径',
      dataList: currencyTrainingChannels,
      checkedList: [dictEntity2 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity2 = value[0];
        trainingChannelsId = value[0].getId();
        trainingChannelsBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
        update();
      },
    );
  }

  // 培训计划列表
  Future<List<GetEducationPlanEntity>> getEducationPlan(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetEducationPlanEntity>>(
      Interface.getEducationPlan,
      queryParameters: {
        'pageNum': index,
        'pageSize': size,
        'planName': searchX, //培训名字 模糊查询
        'trainingType': trainingTypeId, //培训类型
        'trainingChannels': trainingChannelsId, //培训途径
        'trainingLevel': trainingLevelId, //培训级别
        'status': statusId, //培训状态  1：进行中 2：已结束 3.默认  //0：待发起 1：待审批 2：审批中 3：通过 4：驳回
        'startDate': startDate, //	开始时间
        'endDate': endDate, //	结束时间
      },
    ).execute();
    List<GetEducationPlanEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list!;
  }

  ///筛选按钮
  void onFilterButtonPressed() {
    final EducationModController controller = Get.find<EducationModController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  // 重置
  void reset() {
    Get.find<EducationModController>().riskRightScaffoldKey.currentState?.closeEndDrawer();

    // 培训类型
    trainingTypeId = '';
    trainingTypeBack.value = '请选择';

    // 培训级别
    trainingLevelId = '';
    trainingLevelBack.value = '请选择';

    // 培训状态
    statusId = '';
    statusBack.value = '请选择';

    // 培训途径
    trainingChannelsId = '';
    trainingChannelsBack.value = '请选择';

    startDate = '';
    endDate = '';
    globalKey.currentState!.onRefresh();
    update();
  }

  // 确定
  void confirm() {
    Get.back();
    globalKey.currentState!.onRefresh();
    update();
  }

  GetDictAllEntity? dictEntity1;
  GetDictAllEntity? dictEntity2;
  GetDictAllEntity? dictEntity3;
  GetDictAllEntity? dictEntity5;

  ///培训级别
  void selectPxfsVSWR8mRxType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'pxfs_vSWR8mRx');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '培训级别',
      dataList: dictList,
      checkedList: [dictEntity3 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity3 = value[0];
        trainingLevelId = value[0].getId();
        trainingLevelBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  ///培训类型
  void selectPxlxJy31TrQXType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'pxlx_Jy31TrQX');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '培训类型',
      dataList: dictList,
      checkedList: [dictEntity5 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity5 = value[0];
        trainingTypeId = value[0].getId();
        trainingTypeBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  //详情（在线和离线的详情） 培训途径 1:线上 2:线下
  void onClickButtonPressed(GetEducationPlanEntity item) {
    if (item.trainingChannels == '1') {
      Get.toNamed(AppRoutes.onlineTrainingPage, arguments: {'id': item.id, 'isApprove': false, 'isMeTask': false}); //传入计划id 是不是审批 不是任务进入
    } else {
      Get.toNamed(AppRoutes.offLineTrainingPage, arguments: {'id': item.id, 'isApprove': false, 'isMeTask': false}); //传入计划id 是不是审批 不是任务进入
    }
  }

  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  void initCurrencyTrainingChannels() {
    currencyTrainingChannels.clear();
    final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
    getDictAllEntity4.id = '1';
    getDictAllEntity4.dictionaryLabel = '线上';
    currencyTrainingChannels.add(getDictAllEntity4);
    final GetDictAllEntity getDictAllEntity5 = GetDictAllEntity();
    getDictAllEntity5.id = '2';
    getDictAllEntity5.dictionaryLabel = '线下';
    currencyTrainingChannels.add(getDictAllEntity5);
  }

  ///0：待发起 1：待审批 2：审批中 3：通过 4：驳回
  void initCurrencyState() {
    currencyState.clear();
    final GetDictAllEntity getDictAllEntity2 = GetDictAllEntity();
    getDictAllEntity2.id = '0';
    getDictAllEntity2.dictionaryLabel = '待发起';
    currencyState.add(getDictAllEntity2);
    final GetDictAllEntity getDictAllEntity3 = GetDictAllEntity();
    getDictAllEntity3.id = '1';
    getDictAllEntity3.dictionaryLabel = '待审批';
    currencyState.add(getDictAllEntity3);
    final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
    getDictAllEntity4.id = '2';
    getDictAllEntity4.dictionaryLabel = '审批中';
    currencyState.add(getDictAllEntity4);
    final GetDictAllEntity getDictAllEntity5 = GetDictAllEntity();
    getDictAllEntity5.id = '3';
    getDictAllEntity5.dictionaryLabel = '通过';
    currencyState.add(getDictAllEntity5);
    final GetDictAllEntity getDictAllEntity6 = GetDictAllEntity();
    getDictAllEntity6.id = '4';
    getDictAllEntity6.dictionaryLabel = '驳回';
    currencyState.add(getDictAllEntity6);
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          Obx(() => _selectType('状态', statusBack.value)),
          Obx(() => _selectType('培训类型', trainingTypeBack.value)),
          Obx(() => _selectType('培训途径', trainingChannelsBack.value)),
          Obx(() => _selectType('培训级别', trainingLevelBack.value)),
          _alignTitle('培训时间'),
          AppGaps.vGap16,
          CustomSelectTimePeriod(
            startTime: startDate,
            endTime: endDate,
            onConfirm: (start, end) {
              startDate = start;
              endDate = end;
            },
            showBorder: true,
            iconCalendar: AppImages.icon__screen_clock,
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }

  Widget _selectType(String firstName, String name) {
    return Column(
      children: [
        _alignTitle(firstName),
        AppGaps.vGap16,
        Container(
          height: 38.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 1.w, color: const Color(0xFFE3E7EE)),
          ),
          child: Row(
            children: [
              AppGaps.hGap20,
              Expanded(
                child: Text(
                  name,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF495061),
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
              SvgPicture.asset(AppImages.icon_filter_right_arrow),
              AppGaps.hGap20,
            ],
          ),
        ).clickOnce(() {
          if (firstName == '培训类型') {
            selectPxlxJy31TrQXType();
          } else if (firstName == '培训级别') {
            selectPxfsVSWR8mRxType();
          } else if (firstName == '专题') {
          } else if (firstName == '状态') {
            selectCurrencyDangerLevelType();
          } else {
            selectCurrencyTrainingChannels();
          }
        }),
        AppGaps.vGap16,
      ],
    );
  }

  Widget _alignTitle(String title) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
